package cloudoer.su.service.impl;

import cloudoer.su.base.impl.BaseServiceImpl;
import cloudoer.su.entity.Person;
import cloudoer.su.entity.Role;
import cloudoer.su.entity.User;
import cloudoer.su.exception.ServiceException;
import cloudoer.su.service.TeacherService;
import cloudoer.su.service.UserService;
import cloudoer.su.utils.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service("userService")
@Transactional
public class UserServiceImpl extends BaseServiceImpl implements UserService {


    public User login(User user) {
        return userDao.login(user);
    }

    public List<User> getAll() {
        return userDao.getAll();
    }

    public List<User> getByPage(int pageNo, int pageSize) {
        return userDao.getByPage(pageNo, pageSize);
    }

    public User getById(String id) {
        return (User) userDao.getById(id);
    }

    public User getByNumber(String number) {
        return (User) userDao.getByNumber(number);
    }

    public String add(User user, String personNumber, String[] roleNumbers) {
        Person p = (Person) personDao.getByNumber(personNumber);
        if (p == null){
            throw new ServiceException("添加失败，参数错误");
        }
        user.setPerson(p);
        user.setUserName(p.getName());
        Set<Role> set = new HashSet<Role>();
        if (roleNumbers != null){
            for (String number : roleNumbers){
                Role r = (Role) roleDao.getByNumber(number);
                if (r != null){
                    set.add(r);
                }
            }
        }
        user.setRoles(set);
        return userDao.add(user);
    }

    public void update(User user, String personNumber, String[] roleNumbers) {
        Person p = (Person) personDao.getByNumber(personNumber);
        User u = (User) userDao.getById(user.getId());
        if (p == null || u == null){
            throw new ServiceException("修改失败，参数错误");
        }
        u.setPerson(p);
        u.setUserName(p.getName());
        u.setPassword(user.getPassword());
        u.setState(user.getState());
        u.getRoles().clear();
        if (roleNumbers != null){
            for (String number : roleNumbers){
                Role r = (Role) roleDao.getByNumber(number);
                if (r != null){
                    u.getRoles().add(r);
                }
            }
        }
    }

    public void delete(String id) {
        User u = (User) userDao.getById(id);
        if (u == null){
            throw new ServiceException("删除失败，参数错误");
        }
        userDao.delete(id);
    }

    public String importFile(File file) throws ServiceException {
        HSSFWorkbook workbook = null;
        StringBuffer msg = new StringBuffer();
        try {
            workbook = new HSSFWorkbook(new FileInputStream(file));
            HSSFSheet sheet = workbook.getSheetAt(0);
            int cont = sheet.getLastRowNum()+1;
            User u = null;
            Person p = null;
            int successCount = 0;
            int errorCount = 0;
            for (int i = 1; i < cont; i++){
                try {
                    p = (Person) personDao.getByNumber(ExcelUtil.getCallValueToString(sheet.getRow(i).getCell(3)));
                    if (p == null){
                        throw new ServiceException("编号错误");
                    }
                    u = new User();
                    u.setUserName(ExcelUtil.getCallValueToString(sheet.getRow(i).getCell(0)));
                    u.setPassword(ExcelUtil.getCallValueToString(sheet.getRow(i).getCell(1)));
                    u.setState(ExcelUtil.getCallValueToString(sheet.getRow(i).getCell(2)));
                    userDao.add(u);
                    successCount ++ ;
                    if (i+1%20==0){
                        userDao.getSession().flush();
                        userDao.getSession().clear();
                    }
                }catch (ServiceException e){
                    errorCount++;
                    msg.append("[第"+(i+1)+"行]原因:" + e.getErrorMsg());
                    msg.append("<br/>");
                }catch (Exception e){
                    errorCount++;
                    msg.append("[第"+(i+1)+"行]原因:不明...<br/>");
                }
            }
            msg.insert(0,"文件上传成功<br/>导入成功:"+ successCount +"条" + "<br/>导入失败:"+errorCount+ "条 <br/>记录<br/>");
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("导入失败，解析文件错误，请检查文件格式");
        }
        return msg.toString();
    }

    public void exportFile(OutputStream os) throws Exception {
        List<User> list = userDao.getAll();
        // 创建工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建工作表
        HSSFSheet sheet = workbook.createSheet("sheet1");
        //创建一行
        HSSFRow rows = sheet.createRow(0);
        //创建这一行的一个单元格
        rows.createCell(0).setCellValue("用户名");
        rows.createCell(1).setCellValue("密码");
        rows.createCell(2).setCellValue("状态");
        for (int i = 0; i < list.size(); i++){
            rows = sheet.createRow(i+1);
            rows.createCell(0).setCellValue(list.get(i).getUserName());
            rows.createCell(1).setCellValue(list.get(i).getPassword());
            rows.createCell(2).setCellValue(list.get(i).getState());
        }
        workbook.write(os);

    }

    public Set<Role> getRoles(String id) {
        User u = (User) userDao.getById(id);
        if (u == null){
            throw new ServiceException("参数错误");
        }
        if (u.getRoles() == null){
            return new HashSet<Role>();
        }
        return u.getRoles();
    }

    public void deleteRole(String id, String roleId) {
        User u = (User) userDao.getById(id);
        Role r = (Role) roleDao.getById(roleId);
        if (u == null || r == null){
            throw new ServiceException("参数错误，删除失败");
        }
        u.getRoles().remove(r);
    }

    public int getCount() {
        return userDao.getCount();
    }


}
